package com.cheesmo.nzb.codec;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class SplitFileInputStream extends InputStream
{
	String dir = null;
	String[] filenames;
	FileInputStream currentFileInputStream = null;
	int currentSegment = -1;
	boolean deleteWhenFinished;

	public SplitFileInputStream(String dir, String[] filenames, boolean deleteWhenFinished)
			throws FileNotFoundException
	{
		this.dir = dir;
		this.filenames = filenames;
		this.deleteWhenFinished = deleteWhenFinished;
		startNextSegment();
	}

	private void startNextSegment() throws FileNotFoundException {
		this.currentSegment += 1;
		if (this.currentSegment < this.filenames.length)
		{
			try
			{
				if (this.currentFileInputStream != null)
					this.currentFileInputStream.close();
			} catch (IOException e)
			{
				e.printStackTrace();
			}

			this.currentFileInputStream = null;
			this.currentFileInputStream = new FileInputStream(new File(this.dir, this.filenames[this.currentSegment]));
		} else {
			if (this.currentFileInputStream != null) {
				try {
					this.currentFileInputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			this.currentFileInputStream = null;

			if (this.deleteWhenFinished)
				deleteFiles();
		}
	}

	private void deleteFiles()
	{
		for (int i = 0; i < this.filenames.length; i++) {
			File file = new File(this.dir, this.filenames[i]);
			boolean success = file.delete();

			if (!success)
				file.deleteOnExit();
		}
	}

	public int read() throws IOException
	{
		if (this.currentFileInputStream == null)
			return -1;
		int val = this.currentFileInputStream.read();
		if (val == -1) {
			startNextSegment();
			return read();
		}
		return val;
	}

	public static void main(String[] args)
			throws IOException
	{
	}

	public int read(byte[] arg0)
			throws IOException
	{
		if (this.currentFileInputStream == null)
			return -1;
		int val = this.currentFileInputStream.read(arg0);
		if (val == -1) {
			startNextSegment();
			return read(arg0);
		}
		return val;
	}

	public int read(byte[] arg0, int arg1, int arg2) throws IOException {
		if (this.currentFileInputStream == null)
			return -1;
		int val = this.currentFileInputStream.read(arg0, arg1, arg2);
		if (val == -1) {
			startNextSegment();
			return read(arg0, arg1, arg2);
		}
		return val;
	}
}
